package com.zhongc.advance.web.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhongc.advance.common.Constant;
import com.zhongc.advance.common.code.CodeImageGenerator;

@Controller
public class VerCode {
	@Autowired
	private CodeImageGenerator codeImageGenerator;
	
	private final static String CHECK_CODE_SUFFIX = "png";
	
	/**
	 * 生成验证码
	 * @param session
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("checkcode/gen")
	public void genCheckcode(HttpSession session, HttpServletResponse response) throws IOException{
		String code = codeImageGenerator.createImageCode();
		session.setAttribute(Constant.Session.SESSION_CHECKCODE_NAME, code);
		OutputStream out = response.getOutputStream();
		ImageIO.write(codeImageGenerator.createIamge(code), CHECK_CODE_SUFFIX, out);
		out.close();
	}/**
	 * 校验验证码
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value= "checkcode/check", method = RequestMethod.POST)
	public Object checkCheckcode(HttpSession session, String checkcode){
		Map<String, Object> result = new HashMap<String, Object>();
		if(checkcode == null){
			result.put("code", false);
			result.put("message", "验证码不能为空");
			return result;
		}
		String code = (String)session.getAttribute(Constant.Session.SESSION_CHECKCODE_NAME);
		if(code == null){
			result.put("code", false);
			result.put("message", "验证码已过期,请刷新验证码");
			return result;
		}
		if(!code.equalsIgnoreCase(checkcode)){
			result.put("code", false);
			result.put("message", "验证码错误");
			return result;
		}
		result.put("code", true);
		return result;
	}
}
